import  re, time
from datetime import datetime
from lxml import etree
from selenium import webdriver
from templates.logger import Loggers


class today_weather:
    def __init__(self):
        global today, logger
        today = {}
        logger = Loggers().make_logger('getTodayWeather')
        logger.info('Start today clmib loading......')

    def today_weather_jiemian(self, city_code):
        option = webdriver.ChromeOptions()
        option.add_argument("--headless")
        option.add_argument("--disable-gpu")
        option.add_argument("--start-maximized")
        option.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
        global driver
        driver = webdriver.Chrome(chrome_options=option)  # 不打开浏览器
        driver.get('http://www.weather.com.cn/weather1d/%s.shtml' % city_code)
        global source
        source = driver.page_source
        html = etree.HTML(source)
        # print(source)
        province_name = ''
        city_name = ''
        district_name = ''
        # 这个部分城市只有两级
        try:
            province_name = re.findall('<a href="http://\w+.weather.com.cn" target="_blank">(.*?)</a>', source)[0]  # 省
        except:
            logger.warning('province_name is not exist')

        try:
            city_name = re.findall('target="_blank">(.*?)</a><span>&gt;</span>', source)[0]  # 市
        except:
            logger.warning('city_name is not exist')

        try:
            district_name = re.findall('<span>&gt;</span>\n\s*<span>(.*?)</span>', source)[0]  # 区(有点地方是3个)
        except:
            try:
                # 市区-县
                district_name = re.findall('<span>&gt;</span>\s*<span>(.*?)</span>', source)[0]  # 区
            except:
                logger.warning('district_name is not exist')
        adress = province_name + '-' + city_name + '-' + district_name
        now_temperature = re.findall('<div class="tem"><span>(.*?)</span><em>(.*?)</em>', source)  # 当前温度
        now_humidity = html.xpath('//*[@id="today"]/div[2]/div/div[@class="zs h"]/em/text()')  # 当前湿度
        wind_fanx = html.xpath('//*[@id="today"]/div[2]/div/div[@class="zs w"]/span/text()')  # 当前风向
        wind_li = html.xpath('//*[@id="today"]/div[2]/div/div[@class="zs w"]/em/text()')  # 风力
        now_wind = wind_fanx + wind_li
        now_AQI = html.xpath('//*[@id="today"]/div[2]/div/div[@class="zs pol"]/span/a/text()')  # 当前AQI
        # 地区没有aqi,通过判断列表的长度
        if len(now_AQI) == 0:
            today['now_AQI'] = "该地区查不到Aqi,请查看对应的市"
        else:
            today['now_AQI'] = now_AQI
        today['now_temperature'] = now_temperature
        today['now_humidity'] = now_humidity
        today['now_wind'] = now_wind
        return adress

    def today_weather_api(self):
        date = datetime.now().strftime('%Y-%m-%d')
        stop_traffic = re.findall('<span>限行</span><em><b>(.*?)</b>和<b>(.*?)</b></em>', source)
        sunup = re.findall('<span>日出 (.*?)</span>', source)
        sundown = re.findall('<span>日落 (.*?)</span>', source)
        today['date'] = date  # 当天时间
        today['stop_traffic'] = stop_traffic  # 限行
        today['sunup'] = sunup  # 日出
        today['sundown'] = sundown  # 日落

    def start(self, city_code=101270101):
        result = {}
        address = self.today_weather_jiemian(city_code)
        self.today_weather_api()
        logger.info(city_code)
        logger.info(address)
        logger.info(today)
        result['cityCode'] = city_code
        result['cityName'] = address
        result['contents'] = today
        return result

    def __del__(self):
        logger.info('Clmib successful')
        driver.quit()



if __name__ == '__main__':
    st = time.clock()
    resutl = today_weather().start(101270101)
    en = time.clock()

